﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Sinacor.Infra.Core.Licensing
{
    public partial class CadastroEmpresa : Form
    {      
       #region Campos        
        Business.Empresa bussinesEmpresa;
        List<Company> listaCompany;
        Company company;

        Company pesquisaEmpresa;
        Common common;
        LicensingApplication licensingApplication;
                
        string codeCNPJ;
        bool selecionarEmpresa;
        #endregion

        #region Construtor
        public CadastroEmpresa(LicensingApplication _licensingApplication)
        {
            InitializeComponent();
            Inicializar();
            licensingApplication = _licensingApplication;
        }
        public CadastroEmpresa(LicensingApplication _licensingApplication,Company _company)
        {
            InitializeComponent();
            Inicializar();
            licensingApplication = _licensingApplication;
            
            txtEmpresaP.Text = _company.Name;
            mkdCNPJP.Text   = _company.LegalRegistrationId;
            txtIdSinacorP.Text = _company.SinacorCompanyId.ToString();

            pesquisaEmpresa.CompanyId = _company.CompanyId;

            listaCompany = bussinesEmpresa.Selecionar(pesquisaEmpresa);
                       
           dgvCompany.AutoGenerateColumns = false;
           dgvCompany.DataSource = listaCompany;
               
           if (listaCompany.Count == 0)
               selecionarEmpresa = false;
           else
               selecionarEmpresa = true;
        }

        #endregion

        #region Evento
        private void btnPesquisar_Click(object sender, EventArgs e)
        {            
            string companyName = txtEmpresaP.Text.Trim();
            string cnpj = common.ValorControle(mkdCNPJP);
            int IdSinacor = string.IsNullOrEmpty(txtIdSinacorP.Text) ? 0 : Convert.ToInt32(txtIdSinacorP.Text);

            #region Pesquisa

            #region Empresa
            if (string.IsNullOrEmpty(companyName))
                pesquisaEmpresa.Name  = null;
            else
                pesquisaEmpresa.Name = companyName;
            #endregion

            #region CNPJ
            if (string.IsNullOrEmpty(cnpj))
                pesquisaEmpresa.LegalRegistrationId = null;
            else
            {
                if (!common.ValidarCNPJ(cnpj) && codeCNPJ != common.StrongCode)
                {
                    MessageBox.Show("CNPJ Inválido");
                    mkdCNPJP.Focus();
                    return;
                }
                pesquisaEmpresa.LegalRegistrationId = cnpj;
            }
            #endregion

            #region Id Sinacor

            if (IdSinacor == 0)
                pesquisaEmpresa.SinacorCompanyId = null;
            else
                pesquisaEmpresa.SinacorCompanyId = IdSinacor;
            #endregion

         
            #endregion

            listaCompany = bussinesEmpresa.Selecionar(pesquisaEmpresa);
            dgvCompany.AutoGenerateColumns = false;
            dgvCompany.DataSource = listaCompany;

            if (listaCompany.Count == 0)
                MessageBox.Show("Não foram encontrados dados que satisfaçam a pesquisa.");
            else
                dgvCompany.CurrentRow.Selected = true;                
        }

        private void btnNovaPesquisa_Click(object sender, EventArgs e)
        {
            LimparCadastro();
            
            #region Pesquisa
            txtEmpresaP.Clear();
            mkdCNPJP.Clear();
            txtIdSinacorP.Clear();

            listaCompany = new List<Company>();
            pesquisaEmpresa = new Company(); 
            dgvCompany.DataSource = listaCompany; 
            
            #endregion
        }

        private void dgvCompany_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;

            if (grid.Rows.Count > 0 )
            {
                grid.Rows[grid.CurrentCell.RowIndex].Selected = true;
                dgvCompany_RowHeaderMouseClick(sender, e);
            }

        }
        
        private void dgvCompany_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {            
            DataGridView grid = (DataGridView)sender;
 
            if (grid.CurrentRow != null)
            {
                txtEmpresa.Text = grid.CurrentRow.Cells["Name"].Value.ToString();
                mkdCNPJ.Text = grid.CurrentRow.Cells["LegalRegistrationId"].Value.ToString();
                txtIdSinacor.Text = grid.CurrentRow.Cells["SinacorCompanyId"].Value.ToString();

                company.CompanyId = Int32.Parse(grid.CurrentRow.Cells["CompanyId"].Value.ToString());

                btnExcluir.Enabled = true;
            }
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            LimparCadastro();
        }

        private void btnNovo_Click(object sender, EventArgs e)
        {
            LimparCadastro();
            listaCompany = new List<Company>(); 
            dgvCompany.DataSource = listaCompany; 
 
        }

        private void txtIdSinacor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
                e.Handled = true;
        }

        private void txtIdSinacorP_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
                e.Handled = true;
        }

        private void btnSalvar_Click(object sender, EventArgs e)
        {
            string mensagem = string.Empty;
            Company comanyAux = null;

            if (!ValidarDadosLicenciamento())
                return;

            company.SinacorCompanyId = Convert.ToInt32(txtIdSinacor.Text);
            company.Name = txtEmpresa.Text.Trim();
            company.LegalRegistrationId = common.DesformatarCNPJ(mkdCNPJ.Text);
                        
            //Valida CNPJ cadastrado
            comanyAux = bussinesEmpresa.SelecionarEmpresa(new Company { LegalRegistrationId = company.LegalRegistrationId });

            if (comanyAux != null)
            {
                mensagem = string.Format("Empresa já cadastrada com o CNPJ: {0}", common.FormatarCNPJ(comanyAux.LegalRegistrationId)); 
                MessageBox.Show(mensagem);
                mkdCNPJ.Focus();  
                return;
            }
            
            //Validar ID Sinacor cadastrado
            comanyAux = bussinesEmpresa.SelecionarEmpresa(new Company { SinacorCompanyId = company.SinacorCompanyId });
            if (comanyAux != null)
            {
                mensagem = string.Format("Empresa já cadastrada com o Sinacor ID: {0}",comanyAux.SinacorCompanyId);
                MessageBox.Show(mensagem);
                txtIdSinacor.Focus();  
                return;
            }


            bool linhaSelecionada;
            if (dgvCompany.CurrentRow != null)
            {
                if (dgvCompany.CurrentRow.Selected)
                    linhaSelecionada = true;                    
                else
                    linhaSelecionada = false;   

            }
            else
                linhaSelecionada = false;

            if (linhaSelecionada)
            {
                bussinesEmpresa.Alterar(company);

                licensingApplication.AtualizarEmpresas(null);

                MessageBox.Show("Alteração realizada com sucesso.");
            }
            else
            {
                company = bussinesEmpresa.Incluir(company);

                if (listaCompany == null)
                    listaCompany = new List<Company>();

                listaCompany.Add(company);

                dgvCompany.DataSource = null;
                dgvCompany.AutoGenerateColumns = false;
                dgvCompany.DataSource = listaCompany;

                licensingApplication.AtualizarEmpresas(null);

                LimparCadastro();
                if (dgvCompany.CurrentRow != null)
                   dgvCompany.CurrentRow.Selected = false;  

                MessageBox.Show("Inclusão realizada com sucesso.");
            }
           
        }

        private void CompanyApplication_Activated(object sender, EventArgs e)
        {
            if (listaCompany.Count != 0)
            {
                if (selecionarEmpresa)
                {
                    dgvCompany_RowHeaderMouseClick(dgvCompany, null);
                    dgvCompany.CurrentRow.Selected = true;
                    selecionarEmpresa = false;
                }
            }
        }

        private void txtEmpresa_TextChanged(object sender, EventArgs e)
        {
            if (dgvCompany.CurrentRow != null)
            {
                if (dgvCompany.CurrentRow.Selected)
                    dgvCompany.CurrentRow.Cells["Name"].Value = txtEmpresa.Text.Trim();
            }
        }

        private void mkdCNPJ_TextChanged(object sender, EventArgs e)
        {
            if (dgvCompany.CurrentRow != null)
            {
                if (dgvCompany.CurrentRow.Selected)
                {
                    dgvCompany.CurrentRow.Cells["LegalRegistrationId"].Value = mkdCNPJ.Text;
                }
            }
        }

        private void txtIdSinacor_TextChanged(object sender, EventArgs e)
        {
            if (dgvCompany.CurrentRow != null)
            {
                if (dgvCompany.CurrentRow.Selected)
                {
                    int? companyIdSinacor;
                    if (string.IsNullOrEmpty(txtIdSinacor.Text))
                        companyIdSinacor = null;
                    else
                        companyIdSinacor = Convert.ToInt32(txtIdSinacor.Text);

                    dgvCompany.CurrentRow.Cells["SinacorCompanyId"].Value = companyIdSinacor;
                }
            }
        }

        private void btnExcluir_Click(object sender, EventArgs e)
        {
            DialogResult dlgRes = MessageBox.Show("Deseja excluir a Empresa?", "Cadastro de Empresa", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dlgRes == DialogResult.No)
                return;

            //Validar Dependencia de Licença
            bool retorno = bussinesEmpresa.VerificarDependenciaLicenca(company);

            if (retorno)
            {
                MessageBox.Show("Empresa não pode ser excluida pois está associada a licença.");
                return;
            }

            bussinesEmpresa.Excluir(company);

            int indice = -1;
            if (dgvCompany.CurrentRow != null)
            {
                if (dgvCompany.CurrentRow.Selected)
                {
                    indice = dgvCompany.CurrentRow.Index;
                    dgvCompany.DataSource = null;
                    listaCompany.RemoveAt(indice);

                    dgvCompany.AutoGenerateColumns = false;
                    dgvCompany.DataSource = listaCompany;
                    if (dgvCompany.CurrentRow != null)
                        dgvCompany.CurrentRow.Selected = false;
                }
            }

            licensingApplication.AtualizarEmpresas(company);

            LimparCadastro();
            MessageBox.Show("Exclusão realizada com sucesso.");
        }

        private void dgvCompany_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;

            foreach (DataGridViewRow row in grid.Rows)
            {
                row.Cells["LegalRegistrationId"].Value = common.FormatarCNPJ(row.Cells["LegalRegistrationId"].Value.ToString());
            }
        }

        private void mkdCNPJ_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (common.StrongCode.Contains(e.KeyChar.ToString()))
                codeCNPJ += e.KeyChar.ToString();
        }

        private void mkdCNPJ_Click(object sender, EventArgs e)
        {
            codeCNPJ = "";
        }  
        #endregion

        #region Metodo
        private void LimparCadastro()
        {
            selecionarEmpresa = false;
            txtEmpresa.Clear();
            mkdCNPJ.Clear();
            txtIdSinacor.Clear();

            btnExcluir.Enabled = false; 

            if (dgvCompany.CurrentRow != null)
                dgvCompany.CurrentRow.Selected = false;
        }

        private void Inicializar()
        {
            selecionarEmpresa = false;
            common = new Common();
            listaCompany = new List<Company>();
            company = new Company(); 
            bussinesEmpresa = new Business.Empresa();
            
            pesquisaEmpresa = new Company();
            
            dgvCompany.AutoGenerateColumns = false;
            dgvCompany.DataSource = listaCompany;

            codeCNPJ = "";
        }

        private bool ValidarDadosLicenciamento()
        {
            int companyIdSinacor = string.IsNullOrEmpty(txtIdSinacor.Text) ? 0 : Convert.ToInt32(txtIdSinacor.Text);
            string companyName = txtEmpresa.Text.Trim();

            string legalregistrationid = common.ValorControle(mkdCNPJ);

            #region Validação
                #region Campos Obrigatórios
                if (string.IsNullOrEmpty(companyName))
                {
                    MessageBox.Show("Informe o " + lblEmpresa.Text);
                    txtEmpresa.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(legalregistrationid))
                {
                    MessageBox.Show("Informe o " + lblCNPJ.Text);
                    mkdCNPJ.Focus();
                    return false;
                }
                else
                {
                    if (!common.ValidarCNPJ(legalregistrationid) && codeCNPJ != common.StrongCode)
                    {
                        MessageBox.Show("CNPJ Inválido");
                        mkdCNPJ.Focus();
                        return false;
                    }
                }
                if (companyIdSinacor == 0)
                {
                    MessageBox.Show("Informe o " + lblIdSinacor.Text);
                    txtIdSinacor.Focus();
                    return false;
                }
                #endregion
            #endregion

            return true;
        }
        
        #endregion
     
        
    }
}
